#!/usr/local/bin/ruby
# -*- coding: utf-8 -*-

require "mysql"
require 'erubis'
require 'net/http'
require 'uri'
require 'benchmark'

#get時間取得
=begin
def check_site(url) 
  status_code = '000';
  msec = 0;
  size = 0;
  begin
    s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
    sockaddr = Socket.sockaddr_in(80, url)    
    res = ''
    b = Benchmark.measure{
      s.connect(sockaddr)
      s.write "GET / HTTP/1.0\r\n\r\n"
      res = s.read
    }
    msec = (b.real * 1000).to_i
    header, body = res.split("\r\n\r\n", 2)
    if m = header.match(/HTTP\/1.1 (\d+) (\w+)\r\n/)
      status_code = m[1]
    end
    size = body.size
  rescue Exception => e
  end
  p [url, status_code, msec, size]
  [status_code, msec, size]
end
=end
def check_site(url) 
  Net::HTTP.version_1_2
  status_code = '000';
  msec = 0;
  size = 0;
  scheme, userinfo, host, port, registry, path, opaque, query, fragment = URI.split(url)
  
  begin
    http = Net::HTTP.new(host, port);
    http.open_timeout = 120
    http.read_timeout = 120
    
    b = Benchmark.measure{
      begin
        http.start do
          response = http.get(path,{'User-Agent' => "Ruby/#{RUBY_VERSION}"})
          status_code = response.code
          size = response.body.size
        end
      rescue Exception => e
        p e
      end
    }
    msec = (b.real * 1000).to_i
  rescue Exception
  end
  
  p [url, status_code, msec, size]
  [status_code, msec, size]
end

#ファイルを保存する(詳細)
def put_detl(site_id, str)
  file = "/home/code4/public/www/site/"+site_id+".html";
  File.open(file, 'w') {|f|
    f.write str
  }
end

#ファイルを保存する(トップ)
def put_index(str)
  file = "/home/code4/public/www/index.html";
  File.open(file, 'w') {|f|
    f.write str
  }
end

#Y軸を切りの良い数字にする
def convYMax(y_max)
  _convYMax(y_max, 1, y_max)
end

def _convYMax(y_max, keta, pre)
  num = 10
  if y_max.round < num
    if y_max.ceil == y_max.round
      y_max.ceil * keta
    else
      pre.ceil * keta / num
    end
  else
    _convYMax(y_max / Float(num), keta * num, y_max)
  end
end

#DB接続を保存する
def getDB 
  db = Mysql::new("mysql6.naid.jp", "code4", "SIzCxpVgpQ", "code4")
end

#器官を指定して、チェック結果を取得
def query_check_result(db, id, interval) 
  sql = "
SELECT
  r.status_code AS status_code
   , r.msec AS msec
   , date_format(r.checked_date, '%Y-%m-%d %H:%i:%s') AS date
FROM
     check_result r
WHERE
     r.site_id = "+id+"
 AND checked_date >= CURRENT_TIMESTAMP - interval "+interval+"
ORDER BY
     r.id
"
  res = db.query(sql)
 end
